/**
 * 
 */
package co.droidforum.foodx.workers;

import android.os.AsyncTask;

/**
 * @author andres.alzate
 *
 */
public abstract class SimpleWorker {
	
	protected abstract void doWork();
	
	protected abstract void onException(Exception e);
	
	protected abstract void onSuccess();
	
	protected void onBeforeRun() {
		
	}
	
	protected void onAfterRun() {
		
	}
	
	public final void runWorker() {
		AsyncTask<Void, Double, ProcessResponse> task = new AsyncTask<Void, Double, ProcessResponse>(){
			
			@Override
			protected ProcessResponse doInBackground(Void... params) {
				ProcessResponse processResponse = new ProcessResponse();
				try {
					doWork();
				} catch (Exception e) {
					processResponse.setException(e);
				}
				
				return processResponse;
			}

			@Override
			protected void onPostExecute(ProcessResponse result) {
				onAfterRun();
				if(result.getException() != null){
					onException(result.getException());
				} else {
					onSuccess();
				}
			}
		};
		
		onBeforeRun();
		task.execute();
	}
	
	private class ProcessResponse {
		private Exception exception;

		public Exception getException() {
			return exception;
		}

		public void setException(Exception exception) {
			this.exception = exception;
		}
	}
}